# coding=utf-8
'''
Created on 2012-8-26

@author: quanwei
'''
from core import HttpTask
from bs4 import * 
from dzdp import ItemAnalyzer,BaseAnalyzer

#分类页
class ChanelAnalyzer(BaseAnalyzer.BaseAnalyzer):
    #解析网页内容
    def parseHtml(self,html,task):
        newTasks = []
        try:
            soup = BeautifulSoup(html,from_encoding="utf-8")
        except:
            self.complateTask(task,2)
            return newTasks
        
        #
        root = soup.find("ul",{ "class" : "navBlock" })
        if root == None:
            self.complateTask(task,2)
            return newTasks
        current = root.find("ul",{ "class" : "current" })
        if current == None:
            current = root.find("ul",{ "class" : "bigCurrent" })
            cityNode = soup.find("div",{"id":"G_loc-wrap"})
            task.data['city'] = cityNode.get_text().strip()
            
        subs = current.findAll("a")
        
        if len(subs) > 0:
            #不是叶子节点
            for node in subs:         
                newTask = HttpTask.HttpTask()
                newTask.data['city'] = task.data['city']
                newTask.data['category'] = node.contents[0].strip()
                if task.data.get("category") != None:
                    newTask.data['category'] = task.data["category"] + "/" + newTask.data['category']
                newTask.url = "http://www.dianping.com" + node['href']
                newTask.analyzer = ChanelAnalyzer()                 
                
                if not self.existsTask(newTask):
                    self.saveTask(newTask)
                    newTasks.append(newTask)
                    #print(newTask.data['city']+ ":" +newTask.data['category'])
            self.complateTask(task)
        else:
            #叶子结点，开始解析列表,这里并不处理task的状态，交给下一个分析器处理
            task.analyzer = ItemAnalyzer.ItemAnalyzer()
            newTasks.append(task)
            print(task.data['city']+ ":" +task.data['category'])
        return newTasks
            